<template>
	<div id="priceType">
		<v-header>
			<price-header @handleChange="handleChange"></price-header>
		</v-header>
		<v-content class="width-1200">
			<li @click="resetSearch" class="compare my-btn">开始比价</li>
			<el-breadcrumb separator-class="el-icon-arrow-right">
				<el-breadcrumb-item :to="{ path: '/' }">比价</el-breadcrumb-item>
				<el-breadcrumb-item>{{currentType.name}}</el-breadcrumb-item>
			</el-breadcrumb>
			<!--参数-->
			<div class="params">
				<ul>
					<!--原油-->
					<template v-if="canView(0)">
						<li class="my-flex price-type">
							<div class="left"><span>计价方式</span></div>
							<div class="right">
								<el-radio v-model="searchCondition.priceType" v-if="!(value=='fixed'&&currentType && currentType.id==7)" :label="value" v-for="(key,value) in $store.state.price_type" :key="value">{{key}}</el-radio>
							</div>
						</li>
						<li class="my-flex category">
							<div class="left"><span>油种</span></div>
							<div class="right close">
								<el-checkbox :label="item.id" :key="item.id" @change="typesChange" v-model="searchCondition.types" v-if="currentTwoItem.children" v-for="item in currentTwoItem.children">{{item.name}}</el-checkbox>
								<div class="more hover" @click="openClose($event)">
									<span>更多</span><img src="../../assets/priceType/down.png" alt="" />
								</div>
							</div>
						</li>
						<!--材质参数-->
						<li class="my-flex">
							<div class="left"><span>材质</span></div>
							<div class="right my-flex-left">
								<div v-for="(item,index) in searchCondition.params" class="input-suffix my-flex-center">
									<span>{{item.param}}：</span>
									<el-input placeholder="最小值" @change="inputChange" v-model="searchCondition.params[index].start"></el-input> --
									<el-input placeholder="最大值" @change="inputChange" v-model="searchCondition.params[index].end"></el-input>
								</div>
							</div>
						</li>

						<li class="my-flex" v-if="canView(1)">
							<div class="left"><span>合约月</span></div>
							<div class="right">
								<div class="input">
									<el-date-picker v-model="searchCondition.contractDate" :picker-options="pickerBeginDateBefore" value-format="yyyy-MM" format="yyyy-MM" type="month" placeholder="选择月份">
									</el-date-picker>
								</div>
							</div>
						</li>
						<li class="my-flex">
							<div class="left"><span>数量</span></div>
							<div class="right">
								<div class="input qty-input">
									<el-input-number v-model="searchCondition.qty" placeholder="不限" controls-position="right" :min="1" :max="9999"></el-input-number>
									<span class="unit" v-if="unitIdCN">{{unitIdCN}}</span>

								</div>
							</div>
						</li>
						<li class="my-flex" v-if="canView(1)">
							<div class="left"><span>港口</span></div>
							<div class="right">
								<el-radio :label="item.id" :key="item.id" v-model="searchCondition.arrivedPort" v-for="item in $store.state.placePortList">{{item.name}}</el-radio>
							</div>
						</li>
					</template>
					<!--成品油，半成品油-->
					<!--{{currentTwoItem}}-->
					<li class="my-flex" v-if="canView(2)" v-for="item of currentTwoItem.children">
						<div class="left"><span>{{item.name}}</span></div>
						<div class="right">
							<template v-for="item_ of item.children">
								<el-checkbox :label="item__.id" :key="item__.id" v-model="searchCondition.types" v-for="item__ of item_.children">{{item_.name}}/{{item__.name}}</el-checkbox>
							</template>

						</div>
					</li>

					<li class="my-flex" v-if="canView(3)">
						<div class="left"><span>种类</span></div>
						<div class="right">
							<el-checkbox :label="item.id" :key="item.id" v-model="searchCondition.types" v-for="item of currentTwoItem.children">{{item.name}}</el-checkbox>
						</div>
					</li>

					<li class="my-flex" v-if="canView(4)">
						<div class="left"><span>种类</span></div>
						<div class="right">
							<el-checkbox :label="item.id" :key="item.id" v-model="searchCondition.types" v-for="item of treeTwoDate">{{item.name}}</el-checkbox>
						</div>
					</li>
<!--{{$store.state.locationAddress}}-->
					<li class="my-flex" v-if="canView(5)">
						<div class="left"><span>收货地址/提货地址</span></div>
						<div class="right my-flex-between" @click="selectAddress">
							<div class="address">{{searchCondition.address}}</div>
							<img src="../../assets/priceType/address.png" alt="" />
						</div>
					</li>

				</ul>
			</div>

			<div class="list my-flex-between">
				<div class="left">
					<div class="my-flex-between">
						<div class="one-card my-flex-col-around" v-if="latestPrices.length>0" v-for="(item,index) of latestPrices">
							<span v-if="index==0">布伦特</span>
							<span v-if="index==1">WTI</span>
							<span v-if="index==2">汇率</span>
							<li :class="[item.adjustPrice>0 ? 'color-red' : 'color-green']">
								<span>{{item.price}}</span>
								<span>
									{{item.adjustPrice}} <template v-if="index==2">%</template>
								</span>
							</li>
						</div>
					</div>
					<!--表格-->
					<template v-for="(item,index) in list">
						<div class="table-list">
							<div class="title my-flex-between">
								<span class="name" v-if="currentType.id!=5">{{item.group}}</span>
								<span class="name" v-else>{{item.hierarchy}}</span>
								<div class="price" v-if="searchCondition.priceType=='brent'||searchCondition.priceType=='wti'">
									<span>平均贴水: <span class="color-red">$ {{item.average}}</span></span>
									<img v-if="currentType.id!=5" src="../../assets/priceType/upDown.png" @click.stop="showPriceList(item,$event)" alt="" />
								</div>
								<div class="price" v-else>
									<span>平均价格: <span class="color-red">¥ {{item.average}}</span></span>
									<img v-if="currentType.id!=5" src="../../assets/priceType/upDown.png" @click.stop="showPriceList(item,$event)" alt="" />
								</div>
							</div>
							<!--石油石化-->
							<div class="address" v-if="canView(6)">
								<div class="my-flex-center">{{searchCondition.city}}</div>
								<div class="my-flex-center">
									<span>中石油 ({{item.cnpcName ? item.cnpcName : '暂无油库'}})</span>
									<span class="color-red">¥ {{item.cnpc}}</span></div>
								<div class="my-flex-center">
									<span>中石化 ({{item.sinopecName ? item.sinopecName : '暂无油库'}})</span>
									<span class="color-red">¥ {{item.sinopec}}</span></div>
							</div>

							<el-table :data="item.products" size="medium" stripe style="width: 100%">
								<template v-if="currentType.id!=5">
									<el-table-column width="230" prop="userName" label=""></el-table-column>
									<el-table-column width="190" label="">
										<template slot-scope="scope">
											<span class="color-red">{{scope.row.priceCN}}</span>
										</template>
									</el-table-column>
									<el-table-column v-if="canView(6)" width="190" label="">
										<template slot-scope="scope">
											<span>预估运费:¥{{scope.row.freight}}</span>
										</template>
									</el-table-column>
								</template>
								<template v-else>
									<el-table-column width="100" label="">
										<template slot-scope="scope">
											<img class="logo" :src="httptool.ftpUrl+'view/'+scope.row.logo" alt="" />
										</template>
									</el-table-column>
									<el-table-column width="280" label="">
										<template slot-scope="scope">
											<div class="wuzi">
												<span>{{scope.row.name}}</span>
												<span>{{scope.row.userName}}</span>
											</div>
										</template>
									</el-table-column>

									<el-table-column width="90" label="">
										<template slot-scope="scope">
											<span class="color-red">{{scope.row.priceCN}}</span>
										</template>
									</el-table-column>
								</template>

								<el-table-column label="">
									<template slot-scope="scope">
										<div class="my-flex-right">
											<li class="my-btn" @click="goProduct(scope.row)">购买</li>
											<!--<li class="my-btn"><img src="../../assets/priceType/shop.png" alt="" /></li>-->
										</div>
									</template>
								</el-table-column>
							</el-table>
						</div>
						<!--分页-->
						<div class="page-change my-flex-center">
							<div class="my-flex-center">
								<img src="../../assets/priceType/icon_left.png" @click="pageChange(listPage[index]-1,item,index)" alt="" />
								<span class="color-red">{{listPage[index] }}</span>
								<span> / {{Math.ceil(item.total/3)}}</span>
								<img src="../../assets/priceType/icon_right.png" @click="pageChange(listPage[index]+1,item,index)" alt="" />
								<span>跳转至第</span>
								<el-input-number size='mini' v-model="jumpPage[index]" controls-position="right" :precision='0' :min="1" :max="Math.ceil(item.total/3)"></el-input-number>
								<span>页</span>
								<li class="jump bg-red my-btn" @click="pageChange(jumpPage[index],item,index)">跳转</li>
							</div>
						</div>
					</template>
					<!--暂无数据-->
					<v-empty v-if="list.length==0"></v-empty>
				</div>
				<div class="right">
					<!--发标-->
					<div class="releasemark my-flex">
						<div class="my-flex-col-center hover" @click="goMark('/releasemark?id=manys')">
							<img src="../../assets/price/mark1.png" alt="" />
							<li>发标-海量招标</li>
						</div>
						<div class="my-flex-col-center hover" @click="goMark('/releasemark?id=system')">
							<img src="../../assets/price/mark2.png" alt="" />
							<li>发标-系统推荐</li>
						</div>
					</div>
				</div>
			</div>
			<price-chart ref="priceChart" :searchCondition="searchCondition" :productName="productName"></price-chart>
		</v-content>
	</div>
</template>

<script>
	import service from '@/js/services/price/priceType';
	import priceChart from './priceChart.vue';
	import bus from '@/js/common/bus.js';
	export default {
		name: 'priceType',
		components: {
			priceChart
		},
		inject: ['selectAddressShow','hasPermission'],
		data() {
			return {
				searchCondition: {},
				portList: [],
				exchangeRate: {},
				latestPrices: [],
				tableData: [],
				currentType: {
					name: null,
					id: null
				},
				ids: [], //类型ids
				list: [],
				listPage: [],
				jumpPage: [],
				typeIds: [],
				treeTwoDate: [],
				currentTwoItem: {},
				productName: null, //产品名称
				pageNum: 1,
				total: 0,
				pickerBeginDateBefore: {
					disabledDate(time) {
						let year = new Date(time).getFullYear()
						let month = new Date(time).getMonth()
						let today = new Date();
						today.setDate(15);
						today.setMonth(today.getMonth() + 2);
						let now_year = today.getFullYear()
						let now_month = today.getMonth()

						if(year > now_year || (year == now_year && month >= now_month)) {

							return false;
						}
						return true;
					}
				}
			}
		},
		created() {
			this.searchCondition = this.searchCondition_();
		},
		async mounted() {
			this.placePortList();
			this.latestPrice();
			this.resetChange();
			this.getLocation();
			this.$nextTick(() => {
				window.addEventListener('scroll', this.scrollEnd, false);
				bus.$on('test', res => {
					this.selectAddressBack(res);
				})
			})
			let arr = ['price_type'];
			await this.tool.getDirByKey(this, arr);
		},
		watch: {
			'searchCondition.types' () {
				console.log(this.currentType);
			}
		},
		computed: {
			BMap() {
				return this.$store.state.BMap;
			},
			categoryTree() {
				return this.$store.state.categoryTree;
			},
			unitIdCN() {
				if(this.ids.length > 0) {
					let arr = this.categoryTree.filter(item => {
						return item.id == this.ids[0];
					})
					return arr[0].unitIdCN;
				} else {
					return null;
				}
			}
		},
		activated() {
			if(this.$route.query.obj) {
				var obj = JSON.parse(this.$route.query.obj);
				console.log(obj);
			}

			if(obj.id[obj.id.length - 1] == this.currentType.id) {
				return;
			}
			this.handleChange(obj);
		},
		deactivated() {

		},
		beforeDestroy() {
			bus.$off('test', res => {
				this.selectAddressBack(res);
			})
		},
		methods: {
			...service,
			disabledDate(value) {
				console.log(value)
			},
			inputChange() {
				this.searchCondition.types = [];
			},
			typesChange() {
				if(this.currentType && (this.currentType.id == 6 || this.currentType.id == 7)) {
					this.searchCondition.params = this.searchCondition.params.map(item => {
						return {
							param: item.param,
							start: null,
							end: null
						}
					});
				}
			},
			scrollEnd(event) {
				if($(window).scrollTop() + $(window).innerHeight() >= document.body.scrollHeight) {
					this.productSearch();
				}
			},
			resetChange() {
				let obj = {
					name: '原油>国内现货',
					id: [1, 6]
				}

				if(this.$route.query.obj) {
					obj = JSON.parse(this.$route.query.obj);
				}

				this.handleChange(obj);
			},
			handleChange(obj) {
				let id = obj.id[obj.id.length - 1];
				let url = '/priceType?obj=' + JSON.stringify({
					name: obj.name,
					id: obj.id
				})
				this.$router.push(url);
				if(id && id == this.currentType.id) {
					return;
				}
				this.ids = obj.id;
				this.currentType = {
					name: obj.name,
					id: id
				};
				this.list = [];
				//重置搜索条件
				this.searchCondition = this.searchCondition_();
				this.getLocation();
				this.pageNum = 1;
				if(this.currentType.id == 7) {
					this.searchCondition.priceType = 'brent';
				} else if(this.currentType.id == 6) {
					this.searchCondition.priceType = 'fixed';
				}
				//合约月
				let today = new Date();
				today.setDate(15);
				today.setMonth(today.getMonth() + 2);
				this.searchCondition.contractDate = today.getFullYear() + '-' + (today.getMonth() + 1);

				this.productParam();
				if(this.typeIds[0] !== obj.id[0]) {
					this.typeIds = obj.id;
					this.productChildName();
				} else {
					this.setCurrentTwoItem();
				}
			},
			getLocation() {
				let obj = this.$store.state.locationAddress;
				console.log(obj);

				if(!obj.longitude) {
					setTimeout(() => {
						this.getLocation()
					}, 500)
				} else {
					this.searchCondition.longitude = obj.longitude;
					this.searchCondition.latitude = obj.latitude;
					this.searchCondition.address = obj.address;
					this.searchCondition.city = obj.city;
				}
			},
			openClose(ev) {
				let dom = this.tool.getTargetDom($(ev.target), 'right');
				if(dom.hasClass('open')) {
					dom.removeClass('open')
				} else {
					dom.addClass('open');
				}
			},
			resetSearch() {
				this.pageNum = 1;
				this.compare();
			},
			compare() {
				this.checkParams();
				if(this.searchCondition.categoryId == '5') {
					this.searchCondition.deviceFlag = true;
				} else {
					this.searchCondition.deviceFlag = false;
				}
				
				this.productSearch();

			},
			checkParams() {
				if(this.searchCondition.params && this.searchCondition.params.length > 0) {
					this.searchCondition.params = this.searchCondition.params.map(item => {

						if(item.end && item.start > item.end) {
							return {
								param: item.param,
								start: item.end,
								end: item.start
							}
						} else {
							return item;
						}

					});
				}
				console.log(this.searchCondition.params)
				return this.searchCondition.params;
			},
			pageChange(page, item, index) {
				let pageTotal = Math.ceil(item.total / 3);
				if(page < 1 || page > pageTotal) {
					return;
				}
				this.productNextSearch(page, item, index);
				console.log(item)
			},
			showPriceList(item, ev) {
				console.log(ev)

				this.productName = item.group;
				this.$refs.priceChart.show(item);
				//				this.$nextTick(() => {
				//					$('#priceChart_').css({
				//						top: ev.screenY - 30,
				//						left: ev.screenX - 550
				//					})
				//				})
			},
			selectBack(model) {
				console.log(model)
				this.mapmodel.address = model.address;
			},
			goProduct(item) {
				console.log(item)
				this.$router.push('/product?id=' + item.id);
			},
			async goMark(url) {
				let userInfo = this.$store.state.userInfo;
				if(userInfo && userInfo.id && userInfo.type == 0) {
					this.$confirm('您还没有权限,请升级为企业买家，去升级吗?', '提示', {
						confirmButtonText: '去升级',
						cancelButtonText: '再想想',
						type: 'warning'
					}).then(() => {
						this.$router.push('/update');
					}).catch(() => {})
					return;
				}
				await this.hasPermission(5);
				this.$router.push({
					path: url
				});
			},
			selectAddress() {
				if(this.searchCondition.longitude) {
					let mapmodel = {
						longitude: this.searchCondition.longitude,
						latitude: this.searchCondition.latitude,
						address: this.searchCondition.addressPre
					}
					this.selectAddressShow(mapmodel);
				} else {
					this.selectAddressShow();
				}
			},
			selectAddressBack(model) {
				this.searchCondition.address = model.address;
				this.searchCondition.latitude = model.latitude;
				this.searchCondition.longitude = model.longitude;
				this.searchCondition.city = model.city;
			}
		},
		beforeRouteLeave(to, from, next) {
			window.removeEventListener('scroll', this.scrollEnd, false);
			next();
		}
	}
</script>

<style lang="less" src="../../less/page/price/priceType.less"></style>